﻿# --------------------------------------- #
# Virtual Machine Data Disk Configuration #
# --------------------------------------- #
param([string]$virtualMachineService, [string]$virtualMachineName)

Write-Information "Virtual machine '$virtualMachineName' executing disk '$($script.type)' configuration ... " -NoNewLine $true
$userName = $subscription.virtualMachines.adminUserName
$password = $subscription.virtualMachines.password
$netBiosDomain = $subscription.virtualMachines.netBiosDomain
$uri = Get-AzureWinRMUri -ServiceName $virtualMachineService -Name $virtualMachineName
$credential = New-Object System.Management.Automation.PSCredential(($netBiosDomain + "\" + $userName), (ConvertTo-SecureString $password -AsPlainText -Force))
$session = New-PSSession -ComputerName $uri[0].DnsSafeHost -Credential $credential -Port (Get-VirtualMachineInstanceEndpointPort $subscription $virtualMachineName) -UseSSL
switch ($script.type)
{
	"Attach"
	{
		# Attach disk
        if (((Get-AzureVM -ServiceName $virtualMachineService -Name $virtualMachineName).VM.DataVirtualHardDisks | ? {$_.DiskName -eq $script.diskName -and $_.Lun -eq $script.lun}) -eq $null)
        {
		    $operation = Get-AzureVM -ServiceName $virtualMachineService -Name $virtualMachineName | Add-AzureDataDisk -Import -DiskName $script.diskName -LUN $script.lun -HostCaching $script.hostCaching | Update-AzureVM
		    if (!$? -or $operation.OperationStatus -ne "Succeeded") { throw "Data disk operation failed." }
		    # Set drive letter
		    Invoke-Command -Session $session -ScriptBlock {
			    param([string]$label, [string]$letter)
			    while ((Get-WmiObject Win32_Volume -Filter "Label = '$label'") -eq $null) {Start-Sleep -Seconds 5}
			    $volume = Get-WmiObject Win32_Volume -Filter "Label = '$label'"
			    $volume.DriveLetter = "$letter`:"
			    $volume.Put() | Out-Null
		    } -ArgumentList $script.driveLabel, $script.drive
        }
	}
	"Detach"
	{
		# Detach disk
        if (((Get-AzureVM -ServiceName $virtualMachineService -Name $virtualMachineName).VM.DataVirtualHardDisks | ? {$_.Lun -eq $script.lun}) -ne $null)
        {
		    $operation = Get-AzureVM -ServiceName $virtualMachineService -Name $virtualMachineName | Remove-AzureDataDisk -LUN $script.lun | Update-AzureVM
		    if (!$? -or $operation.OperationStatus -ne "Succeeded") { throw "Data disk operation failed." }
        }
	}
	default
	{
		throw "Disk operation type '$($script.type)' is not supported."
	}
}
Remove-PSSession $session
Write-Text "done."